package thn.glf.org.personalfinancial;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;


import thn.glf.org.lib.DialogButton;
import thn.glf.org.lib.LocationCurent;
import thn.glf.org.lib.MessageBox;
import thn.glf.org.personalfinancial.objData.FinancialDay;
import thn.glf.org.personalfinancial.objData.FinancialMonth;

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class MoneyOfDayActivity extends Activity {
	static final int DATE_DIALOG_ID = 999;
	static final int TIME_DIALOG_ID = 998;
	private int year;
	private int month;
	private int day;
	private int hourOfDay;
	private int minute;
	private String Coordinates = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.moneyofday);
		Button btntimes = (Button) findViewById(R.id.btntimes);
		Button btndate = (Button) findViewById(R.id.btndate);
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		String currentdatetime = formatter.format(currentDate.getTime());
		btntimes.setText(currentdatetime.substring(11, 16));
		hourOfDay = Integer.parseInt(currentdatetime.substring(11, 16)
				.substring(0, 2));
		minute = Integer.parseInt(currentdatetime.substring(11, 16).substring(
				3, 5));
		btntimes.setOnClickListener(Time_click);
		btndate.setText(currentdatetime.substring(0, 10));
		this.year = Integer.parseInt(currentdatetime.substring(0, 10)
				.substring(0, 4));
		this.month = Integer.parseInt(currentdatetime.substring(0, 10)
				.substring(5, 7));
		this.day = Integer.parseInt(currentdatetime.substring(0, 10).substring(
				8, 10));
		btndate.setOnClickListener(Date_click);
		Button btnSave = (Button) findViewById(R.id.btnSave);
		btnSave.setOnClickListener(Save_click);
		Button btnCancle = (Button) findViewById(R.id.btnCancle);
		btnCancle.setOnClickListener(Cancle_Click);
		Button btnGPS = (Button) findViewById(R.id.btnGPS);
		btnGPS.setOnClickListener(GPS_Click);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.money_of_day, menu);
		return true;
	}

	private OnClickListener GPS_Click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		
			Geocoder geocoder = new Geocoder(getApplicationContext());
			LocationCurent mGPS = new LocationCurent(getApplicationContext());

			if (mGPS.canGetLocation) {

				Coordinates = mGPS.getLatitude() + "," + mGPS.getLongitude();
			} else {
				Coordinates = "";
				// can't get the location
			}
			EditText txtplace = (EditText) findViewById(R.id.txtplace);
			String strAddressOrder = "";
			try {
				List<Address> addresses = geocoder.getFromLocation(
						mGPS.getLatitude(), mGPS.getLongitude(), 1);
				if (addresses.size() > 0) {
					Address address = addresses.get(0);

					for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
						strAddressOrder += address.getAddressLine(i);
					}
					txtplace.setText(strAddressOrder);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				txtplace.setText(strAddressOrder);
			}
		}
	};
	OnClickListener Time_click = new OnClickListener() {

		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(TIME_DIALOG_ID);
		}
	};
	OnClickListener Date_click = new OnClickListener() {

		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(DATE_DIALOG_ID);
		}
	};
	OnClickListener Save_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Button Days = (Button) findViewById(R.id.btndate);
			Button Times = (Button) findViewById(R.id.btntimes);
			EditText ProductName = (EditText) findViewById(R.id.txtproductname);
			EditText Note = (EditText) findViewById(R.id.txtNote);
			EditText Place = (EditText) findViewById(R.id.txtplace);
			EditText PriceMoney = (EditText) findViewById(R.id.txtmoney);
			FinancialDay financialDay = new FinancialDay();
			financialDay.setmContext(getApplicationContext());
			financialDay.setCoordinates(Coordinates);
			
			financialDay.setDays(Days.getText().toString().replace("/", ""));
			financialDay.setDayID(financialDay.initDayID(financialDay.getDays())+1);
			financialDay.setNote(Note.getText().toString());
			financialDay.setPlace(Place.getText().toString());
			financialDay.setPriceMoney(Double.parseDouble("0"
					+ PriceMoney.getText().toString()));
			financialDay.setProductName(ProductName.getText().toString());
			financialDay.setTimes(Times.getText().toString().replace(":", ""));
			if (CheckError()) {
				financialDay.setmContext(getApplicationContext());
				financialDay.Add(financialDay);
				FinancialMonth financialMonth=new FinancialMonth();
				financialMonth.setmContext(getApplicationContext());
				if(!financialMonth.CheckExist(financialDay.getDays())){
					SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
					int year=Integer.parseInt(financialDay.getDays().substring(0,4));
					int month=Integer.parseInt(financialDay.getDays().substring(4,6));
					Calendar dateketso = Calendar.getInstance();
					dateketso.set(year, month-1, Main.ngayketso);
					String DateStart = formatter.format(dateketso.getTime());
					dateketso.add(Calendar.MONTH, 1);
					dateketso.add(Calendar.DAY_OF_MONTH, -1);
					String DateEnd = formatter.format(dateketso.getTime());
					financialMonth.setMonthID(month);
					financialMonth.setMonthFrom(DateStart);
					financialMonth.setMonthTo(DateEnd);
					financialMonth.Add(financialMonth);
				}
				
				
			} else {
				return;
			}
			finish();
		}
	};

	private boolean CheckError() {
		EditText ProductName = (EditText) findViewById(R.id.txtproductname);
		if (ProductName.getText().toString().trim().isEmpty()) {
			MessageBox.Show(this, "Vui lòng nhập sản phẩm sử dụng",
					DialogButton.OK);
			ProductName.requestFocus();
			return false;
		}
		EditText PriceMoney = (EditText) findViewById(R.id.txtmoney);
		if (Double.parseDouble("0" + PriceMoney.getText()) == 0) {
			MessageBox.Show(this, "Vui lòng nhập số tiền sử dụng",
					DialogButton.OK);
			PriceMoney.requestFocus();
			return false;
		}
		Button Days = (Button) findViewById(R.id.btndate);
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		String currentdatetime = formatter.format(currentDate.getTime());
		if (Days.getText().toString().replace("/", "")
				.compareTo(currentdatetime) > 0) {
			MessageBox.Show(this,
					"Ngày sử dụng tiền phải nhỏ hơn ngày hôm nay",
					DialogButton.OK);
			return false;
		}

		return true;
	}

	OnClickListener Cancle_Click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			finish();
		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date

			return new DatePickerDialog(this, datePickerListener, year,
					month - 1, day);
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, timePickerListener, hourOfDay,
					minute, true);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			Button btndate = (Button) findViewById(R.id.btndate);
			btndate.setText(selectedYear + "/"
					+ String.format("%02d", (selectedMonth + 1)) + "/"
					+ String.format("%02d", selectedDay));

		}
	};
	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			Button btntimes = (Button) findViewById(R.id.btntimes);
			btntimes.setText(String.format("%02d", hourOfDay) + ":"
					+ String.format("%02d", minute));
		}
	};

}
